<?php
namespace BLL\DAO;
use Illuminate\Support\Facades\DB as DB;

class SeederBuilder{
    
    public static function dataSeeding($filename){
        echo $filename;
        $jsonObj= self::readFromFile($filename);
        echo $tableName = $jsonObj['realTableName'];
        echo $coloum_number = sizeof($jsonObj["divs"]);
        for($i=0;$i<$coloum_number;$i++){
            /* @var $jsonObj type */
            $div_coloum_val[$i] = $jsonObj["divs"][$i]['values'];
            $div_coloum_name[$i] = $jsonObj["divs"][$i]['name'];
        }
        $fetch_values = $jsonObj["values"][0]["values"];
        var_dump($div_coloum_name);
        var_dump($div_coloum_val);
        var_dump($fetch_values);
        var_dump($jsonObj["values"][0]["name"]);
        $value_name = $jsonObj["values"][0]["name"];
        self::recursive(array(), 0,$div_coloum_val,$div_coloum_name,$fetch_values,$value_name,0,$tableName);
    }
    //loop value
    private static function  recursive($valarr, $divIndex,$divs,$divs_name,$value,$value_name,$cnt,$tableName){
          foreach ($divs[$divIndex] as $v) {
            $valarr[$divs_name[$divIndex]] = $v;
            if ($divIndex === count($divs) - 1) {
                $valarr[$value_name] = $value[$cnt];
                $cnt++;
                //insert into db
                DB::table($tableName)->insert([
                        $valarr
                        ]);
            } else {
                $cnt = self::recursive($valarr, $divIndex + 1,$divs,$divs_name,$value,$value_name,$cnt,$tableName);
                
            }
          }
          return $cnt;
          
    }
    
    //Read value from file
    private static function readFromFile($configName=null){
        $path = str_replace("\\", DIRECTORY_SEPARATOR, $GLOBALS["AppConfig"]["parameter"]);
        $path = str_replace("/", DIRECTORY_SEPARATOR, $path); 
        if (!strrchr($path, DIRECTORY_SEPARATOR)) {
            $path = $path . DIRECTORY_SEPARATOR;
        }
        $filename= \app_path()."\\".$path.$configName.".json";
            if(file_exists($filename)){
                $str = file_get_contents($filename);
                $jsonObject = json_decode($str,true);
                return $jsonObject;
            }
        }
}